package cn.work.control;

import cn.work.bean.userbean;
import cn.work.service.userService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
* 登录界面的servlet方法
*
* */
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        userbean  user = null;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        user = new userbean();
        user.setUsername(username);
        user.setPassword(password);
        //将信息打印到控制台，测试前端传过来的数据是否有效
        System.out.printf("servlet账号为：%s，密码为%s",user.getUsername(),user.getPassword());
        userService userlog = new userService();
        user = userlog.login(user);
        if(user!=null){
            try {
                HttpSession session = request.getSession();
                session.setAttribute("user",user);
                System.out.println(user.getIdentity());
                if(user.getIdentity()==1)
                    response.sendRedirect("admin/admin_yuyue.jsp");
                else
                    response.sendRedirect("user/shouye.jsp");
            } catch (IOException e) {
                e.printStackTrace();
                // 重新抛出异常，以便在更上层的调用者中处理
                System.err.println("重定向到admin.jsp时发生错误: " + e.getMessage());
            }
        }
        else{
            request.setAttribute("failMsg","用户名或密码错误,或未注册！请重新登陆或去注册！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            System.err.println("账号密码错误: ");
        }
    }
}
